import React, { Component } from 'react'
import axios from 'axios'

import demoStyle from './demo.module.scss'

import PropTypes from 'prop-types'

import styled from 'styled-components' // css in js方案

const BoxContainer = styled.div`
  /* width: 1rem; */
  /* height: 1rem; */
  max-height: 100px;
  overflow: auto;
  background: lightblue;
`

// css in js

const ListTitle = (props) => {
  const { list, tabIndex, handleTabClick } = props
  return (
    <>
      {list.map((item, index) => {
        return (
          <span
            className={tabIndex === index ? `${demoStyle.title} ${demoStyle.active}` : demoStyle.title}
            onClick={() => {
              handleTabClick && handleTabClick(index, item)
            }}
            key={item.name}
            style={{ margin: 5 }}
          >
            {item.name}
          </span>
        )
      })}
    </>
  )
}

// 设置默认值
ListTitle.defaultProps = {
  tabIndex: 0,
}
// 校验数据结构
ListTitle.propTypes = {
  tabIndex: PropTypes.number,
  list: PropTypes.array,
}

const ListContent = (props) => {
  const { listChildren, handleRemoveClick } = props
  return (
    <>
      <ul>
        {listChildren.map((item, index) => {
          return (
            <li
              key={item.name}
              onClick={() => {
                handleRemoveClick && handleRemoveClick(index)
              }}
            >
              {item.name}
            </li>
          )
        })}
      </ul>
    </>
  )
}

export default class index extends Component {
  state = {
    list: [],
    tabIndex: 0,
    listChildren: [],
  }
  async componentDidMount() {
    const data = await axios.get('/data.json')
    this.setState({ list: data.data, listChildren: data.data[0].children })
  }
  render() {
    const { list, tabIndex, listChildren } = this.state
    return (
      <div>
        <BoxContainer>
          <ListTitle
            list={list}
            tabIndex={tabIndex}
            handleTabClick={(index, item) => {
              this.setState({ tabIndex: index, listChildren: item.children })
            }}
          />

          <ListContent
            listChildren={listChildren}
            handleRemoveClick={(index) => {
              let copy = [...listChildren]
              copy.splice(index, 1)
              this.setState({ listChildren: copy })
            }}
          />
        </BoxContainer>
      </div>
    )
  }
}
